﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using FreeDict;

namespace MetroDictionary
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        private static FreeDictionary _dict;
        private bool _loaded;
        private string _searchText;
        private int _selectedIndex;
        private string _selectedWord;
        private string[] _words;
        private static Task _loadingTask;

        public MainPageViewModel()
        {
            Load();
        }

        public bool IsLoading
        {
            get { return !_loaded; }
        }

        public IEnumerable<string> Words
        {
            get { return _words; }
        }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                OnPropertyChanged("SearchText");
                DoSearch();
            }
        }

        public int SelectedIndex
        {
            get { return _selectedIndex; }
            set
            {
                _selectedIndex = value;
                OnPropertyChanged("SelectedIndex");
            }
        }

        public string SelectedWord
        {
            get { return _selectedWord; }
            set
            {
                _selectedWord = value;
                OnPropertyChanged("SelectedWord");
                OnPropertyChanged("Translation");
            }
        }

        public string Translation
        {
            get
            {
                //return HtmlUtilities.ConvertToText(_dict.GetTranslation(SelectedWord));
                return GetTranslation(SelectedWord);
            }
        }

        public string GetTranslation(string word)
        {
            return _dict.GetTranslation(word);
        }

        public async Task WaitForLoadingAsync()
        {
            await _loadingTask;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void DoSearch()
        {
            SelectedWord = _dict.FindWord(_searchText);
        }

        private async void Load()
        {
            if (_dict == null)
            {
                _dict = new FreeDictionary();
                _loadingTask = _dict.LoadAsync(@"Assets\eng_rus_eng.txt");
                await _loadingTask;
            }
            _loaded = true;

            _words = _dict.GetWords().ToArray();
            OnPropertyChanged("Words");
            OnPropertyChanged("IsLoading");
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}